#include "mdb.h"
#include "mtuya.h"
#include "mdb_data.h"
#include "user_thread.h"

#include "tal_api.h"
#include "tkl_gpio.h"

#include "led.h"

/* Tuya thread handle */
static THREAD_HANDLE mdb_thread = NULL;

static void cb_mdb_led_flick(int32_t dtype, void *userdata)
{
	int32_t value = mdb_get_data(dtype);

	if (value) {
		tkl_gpio_write(LED_OUTPUT_PIN, TUYA_GPIO_LEVEL_HIGH);
	} else {
		tkl_gpio_write(LED_OUTPUT_PIN, TUYA_GPIO_LEVEL_LOW);
	}
}

static void mdb_thread_main(void *arg)
{
	int32_t count = 0;
    OPERATE_RET rt = OPRT_OK;

	log_error("mdb_thread_main running\n");
#if 0
    /*GPIO output init*/
    TUYA_GPIO_BASE_CFG_T out_pin_cfg = {
        .mode = TUYA_GPIO_PUSH_PULL, .direct = TUYA_GPIO_OUTPUT, .level = TUYA_GPIO_LEVEL_LOW};
    TUYA_CALL_ERR_LOG(tkl_gpio_init(LED_OUTPUT_PIN, &out_pin_cfg));

	mdb_register_listerner(LED0, cb_mdb_led_flick, NULL, 0);

	#endif
//	led_flick_fast_l1();
//	led_flick_fast_l1();
	led_flick_fast_l2();
	led_flick_slow();
//	led_set_off();

	while(1) {
		mdb_handler_loop();
		tal_system_sleep(100);
		count++;
		if (count <= 5) {
//			led_flick_fast();
//			tkl_gpio_write(LED_OUTPUT_PIN, TUYA_GPIO_LEVEL_HIGH);
		} else if (count <= 10) {
//			led_flick_slow();
//			tkl_gpio_write(LED_OUTPUT_PIN, TUYA_GPIO_LEVEL_LOW);
		} else {			
			count = 0;
		}

//		if (count == 10)
//			log_info("mdb_thread is alive\n");
	}

    tal_thread_delete(mdb_thread);
    mdb_thread = NULL;
}


void mdb_app_init(void)
{
 	OPERATE_RET op_ret;
	THREAD_CFG_T thrd_param = {4096, 4, "app_mdb_main"};
	
	log_error("mdb_app_init start\n");

	mdb_service_init(mdb_nodes, ARRAY_SIZE(mdb_nodes));
	
	tuya_service_init(mty_dpattr, ARRAY_SIZE(mty_dpattr));

	op_ret = tal_thread_create_and_start(&mdb_thread, NULL, NULL, mdb_thread_main, NULL, &thrd_param);
	if (op_ret != OPRT_OK) {
		log_error("Create app_mdb_thread failed\n");
	}

	
	log_error("mdb_app_init complite\n");

	return;
}


